#!/usr/bin/env python3
import sys
import requests
import socket  
  
def get_local_ip():  
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    try:  
        s.connect(('10.255.255.255', 1))  
        ip = s.getsockname()[0]  
    except Exception:  
        ip = '127.0.0.1'  
    finally:  
        s.close()  
    return ip  
  
def write_stdout(s):
    # only eventlistener protocol messages may be sent to stdout
    sys.stdout.write(s)
    sys.stdout.flush()

def write_stderr(s):
    sys.stderr.write(s)
    sys.stderr.flush()

EVENT_NAME = {
   "PROCESS_STATE_EXITED": "进程退出💀",
   "PROCESS_STATE_RUNNING":"进程启动😄"
}

def SendBot(msg):
    URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5b623d7d-9667-46cd-b873-d4885a8e9f2f"
    mHeader = {'Content-Type': 'application/json; charset=UTF-8'}
    mBody = {
        "msgtype": "text",
        "text": {
                "content": msg
              }
    }
    requests.post(url=URL, json=mBody, headers=mHeader)

def main():
    while 1:
        # transition from ACKNOWLEDGED to READY
        write_stdout('READY\n')

        # read header line and print it to stderr
        line = sys.stdin.readline()
        write_stderr(line)

        # read event payload and print it to stderr
        headers = dict([ x.split(':') for x in line.split() ])
        data = sys.stdin.read(int(headers['len']))
        write_stderr(data)

        payloads = dict([ x.split(':') for x in data.split() ])

        event_name = headers["eventname"] 
        pid = payloads["pid"]
        processname = payloads["processname"]
        ip = get_local_ip()
        SendBot(f"{ip} {processname} {EVENT_NAME[event_name]} pid:{pid}\n")

        # transition from READY to ACKNOWLEDGED
        write_stdout('RESULT 2\nOK')

if __name__ == '__main__':
    main()
